import taosrest

def column_exists(cursor, db_name, stable_name, column_name):
    try:
        # 查询超级表的列信息
        cursor.execute(f"DESCRIBE {db_name}.{stable_name}")
        columns = cursor.fetchall()
        # 检查目标列是否存在
        for col in columns:
            if col[0] == column_name:
                return True
        return False
    except Exception as e:
        print(f"❌ 查询列信息失败: {e}")
        return False

def add_column_if_not_exists():
    try:
        conn = taosrest.connect(
            url="http://192.168.1.251:6041",
            user="root",
            password="taosdata"
        )
        cursor = conn.cursor()
        db_name = "syslogdb"
        stable_name = "syslog_logs"
        column_name = "translated_message"

        if not column_exists(cursor, db_name, stable_name, column_name):
            cursor.execute(f"ALTER STABLE {db_name}.{stable_name} ADD COLUMN {column_name} NCHAR(4096)")
            print(f"✅ 成功添加列: {column_name}")
        else:
            print(f"ℹ️ 列 {column_name} 已存在，无需添加。")
    except Exception as e:
        print(f"❌ 操作失败: {e}")
    finally:
        if 'conn' in locals():
            conn.close()

add_column_if_not_exists()